#include <QClipboard>
#include <QImage>
#include <QPixmap>
#include <QDebug>
#include <QDir>
#include "HttpClientView.h"
#include "ui_httpclientview.h"
#include "qaesencryption.h"
#include <QMessageBox>

void MySleep(int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

HttpClientView::HttpClientView(QWidget *parent) :
    QWidget(parent), mHttpClient(NULL),
    ui(new Ui::HttpClientView)
{
    ui->setupUi(this);
    init();
    initUI();
    initSlot();
}

HttpClientView::~HttpClientView()
{
    if (mHttpClient) {
        delete mHttpClient;
        mHttpClient = NULL;
    }
    delete ui;
}

void HttpClientView::init()
{
    mHttpClient = new HttpClient();
    connect(mHttpClient, SIGNAL(postFinish(QString,int,QByteArray&)), this, SLOT(postFinishSlot(QString,int,QByteArray&)));
    connect(mHttpClient, SIGNAL(httpError(QNetworkReply::NetworkError)), this, SLOT(httpErrorSlot(QNetworkReply::NetworkError)));

    //QString strResults="play_auth_token=eyJHZXRQbGF5SW5mb1Rva2VuIjoiQWN0aW9uPUdldFBsYXlJbmZvXHUwMDI2VmVyc2lvbj0yMDE5LTAzLTE1XHUwMDI2WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTZcdTAwMjZYLUFtei1DcmVkZW50aWFsPUFLTFRNbVkzWWpnNU5XVXpaRFl3TkdJMk4ySmpNbUZoWVdJME56Rm1ZV1F4WTJZJTJGMjAyMjEwMjclMkZjbi1ub3J0aC0xJTJGdm9kJTJGYXdzNF9yZXF1ZXN0XHUwMDI2WC1BbXotRGF0ZT0yMDIyMTAyN1QwNTM4MzZaXHUwMDI2WC1BbXotRXhwaXJlcz0yMTYwMFx1MDAyNlgtQW16LU5vdFNpZ25Cb2R5PVx1MDAyNlgtQW16LVNpZ25hdHVyZT1kYjU2NmFkMjJjMDZhOTA3NDg4MmVjMzc1Y2QxMDY0Yjg0YTdjMThlZTI5ZWE3ODYzMGUxYTg5MDhkNDYwMWNkXHUwMDI2WC1BbXotU2lnbmVkSGVhZGVycz1cdTAwMjZYLUFtei1TaWduZWRRdWVyaWVzPUFjdGlvbiUzQlZlcnNpb24lM0JYLUFtei1BbGdvcml0aG0lM0JYLUFtei1DcmVkZW50aWFsJTNCWC1BbXotRGF0ZSUzQlgtQW16LUV4cGlyZXMlM0JYLUFtei1Ob3RTaWduQm9keSUzQlgtQW16LVNpZ25lZEhlYWRlcnMlM0JYLUFtei1TaWduZWRRdWVyaWVzJTNCYWlkJTNCYXV0aF9wb2xpY3klM0Jmb3JtYXRfdHlwZSUzQnNzbCUzQnN0cmVhbV90eXBlJTNCdXJsX3R5cGUlM0J2aWRlb19pZFx1MDAyNmFpZD00NzgzXHUwMDI2YXV0aF9wb2xpY3k9ZXlKMmJTSTZNeXdpZFdsa0lqb2lNak0zTlRNNU5qSTFOamt5TVRjeU1DSjlcdTAwMjZmb3JtYXRfdHlwZT1obHNcdTAwMjZzc2w9MVx1MDAyNnN0cmVhbV90eXBlPWV2aWRlb1x1MDAyNnVybF90eXBlPTZcdTAwMjZ2aWRlb19pZD12MDJiMDFnMTAwMDBjODV0Z3VyYzc3dWN2ZG9qaDA5ZyIsIlZlcnNpb24iOiJ2MSJ9";
    ui->plainTextEdit->setPlainText("在Fiddler查找 \nstudent-api.iyincaishijiao.com\n/ep/cell/detail/");
}

void HttpClientView::initUI()
{
    //ui->labelImage->setStyleSheet("{border:2px dotted #242424;}");
    ui->cBoxMethod->setCurrentIndex(1);
    ui->cBoxScheme->hide();
    ui->cBoxMethod->hide();
    timer=new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(onTimer()));
    //timer->start(500);
}

void HttpClientView::initSlot()
{
    connect(ui->btnExecute, SIGNAL(clicked()), this, SLOT(onBtnExecuteClicked()));
    connect(ui->BtnClear, SIGNAL(clicked()), this, SLOT(onBtnClearClicked()));
    connect(ui->btnCopy, SIGNAL(clicked()), this, SLOT(onBtnCopyClicked()));

    connect(ui->btnDecode, SIGNAL(clicked()), this, SLOT(onBtnDecodeClicked()));
    connect(ui->btnClear_2, SIGNAL(clicked()), this, SLOT(onBtnClear_2Clicked()));
    connect(ui->btnCopy_2, SIGNAL(clicked()), this, SLOT(onBtnCopy_2Clicked()));

    connect(ui->btnAuto1, SIGNAL(clicked()), this, SLOT(onBtnAuto1Clicked()));
    connect(ui->btnAuto2, SIGNAL(clicked()), this, SLOT(onBtnAuto2Clicked()));
}

void HttpClientView::onBtnExecuteClicked()
{
    QString str;
    QString strResults=ui->plainTextEdit_2->toPlainText();
    strResults = strResults.mid(16);
    QByteArray b1=strResults.toLatin1();
    QByteArray b2=QByteArray::fromBase64(b1);

    str.prepend(b2);
    int p1=str.indexOf("Action=");
    int p2=str.lastIndexOf("Version");
    strResults=str.mid(p1,p2-p1-3);
    strResults.replace("\\u0026","&");
    str="https://vod.bytedanceapi.com/?"+strResults;

    int scheme = ui->cBoxScheme->currentIndex();
    int method = ui->cBoxMethod->currentIndex();
    ui->plainTextEdit->appendPlainText("request...");
    qDebug()<<QString("http scheme : %1, method: %2").arg(scheme).arg(method);

    if (0 == method) {
        QString url("https://httpbin.org/post");
        mHttpClient->doRequest(HttpClient::POST, url);
    } else if (1 == method) {
        //QString url("https://vod.bytedanceapi.com/?Action=GetPlayInfo&Version=2019-03-15&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKLTMmY3Yjg5NWUzZDYwNGI2N2JjMmFhYWI0NzFmYWQxY2Y%2F20221027%2Fcn-north-1%2Fvod%2Faws4_request&X-Amz-Date=20221027T053836Z&X-Amz-Expires=21600&X-Amz-NotSignBody=&X-Amz-Signature=db566ad22c06a9074882ec375cd1064b84a7c18ee29ea78630e1a8908d4601cd&X-Amz-SignedHeaders=&X-Amz-SignedQueries=Action%3BVersion%3BX-Amz-Algorithm%3BX-Amz-Credential%3BX-Amz-Date%3BX-Amz-Expires%3BX-Amz-NotSignBody%3BX-Amz-SignedHeaders%3BX-Amz-SignedQueries%3Baid%3Bauth_policy%3Bformat_type%3Bssl%3Bstream_type%3Burl_type%3Bvideo_id&aid=4783&auth_policy=eyJ2bSI6MywidWlkIjoiMjM3NTM5NjI1NjkyMTcyMCJ9&format_type=hls&ssl=1&stream_type=evideo&url_type=6&video_id=v02b01g10000c85tgurc77ucvdojh09g");
        mHttpClient->doRequest(HttpClient::GET, str);
    }
}

void HttpClientView::onBtnClearClicked()
{
    ui->plainTextEdit->clear();
    ui->plainTextEdit_2->clear();
}

void HttpClientView::onBtnCopyClicked()
{
    QClipboard *clipboard = QApplication::clipboard();   //获取系统剪贴板指针
    //QString originalText = clipboard->text();	     //获取剪贴板上文本信息
    clipboard->setText(ui->plainTextEdit->toPlainText());		             //设置剪贴板内容</span>
}

void HttpClientView::onBtnDecodeClicked()
{
    QString str;
    QString str1=ui->lineEdit->text();
    if(str1.startsWith("data=") && str1.lastIndexOf("=")>10)
    {
        int p1=str1.indexOf('=');
        int p2=str1.indexOf(':');
        int p3=str1.lastIndexOf('=');

        QString str2=str1.mid(p1+1,p2-p1-1);
        QString str3=str1.mid(p2+1,p3-p2);
        qDebug()<<str2;
        qDebug()<<str3;
        QString str4=str2.mid(0,16);
        QString str5=str2.mid(16);
        QString str6=str5+str4;
        qDebug()<<str6;
        QString inputStr=str3;
        QString key=str6;
        QString iv=str5;

        QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::CBC, QAESEncryption::ZERO);
        QByteArray data = QByteArray::fromBase64(inputStr.toLocal8Bit(), QByteArray::Base64Encoding);
        QByteArray decodeText = encryption.decode(data, key.toLocal8Bit(), iv.toLocal8Bit());
        str=decodeText.left(16);
        qDebug()<<str;
        ui->lineEdit_2->setText(str);
    }

}

void HttpClientView::onBtnClear_2Clicked()
{
    ui->lineEdit->clear();
    ui->lineEdit_2->clear();
}

void HttpClientView::onBtnCopy_2Clicked()
{
    QClipboard *clipboard = QApplication::clipboard();   //获取系统剪贴板指针
    //QString originalText = clipboard->text();	     //获取剪贴板上文本信息
    clipboard->setText(ui->lineEdit_2->text());		             //设置剪贴板内容</span>
}

void HttpClientView::onBtnAuto1Clicked()
{
    ui->lineEdit_2->clear();
    ui->plainTextEdit->clear();
    onBtnDecodeClicked();
    onBtnExecuteClicked();
    timer->start(500);
}

void HttpClientView::onBtnAuto2Clicked()
{
    QStringList sl;
    QString filename = QApplication::applicationDirPath() + QDir::separator() + "aa.har";
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return ;

    QTextStream in(&file);
    QString line = in.readLine();
    while (!line.isNull())
    {
        if(line.startsWith("play_auth_token"))
        {
            line=line.replace(15,1,"=");
            ui->plainTextEdit_2->setPlainText(line);
        }
        else if(line.startsWith("data") && line.endsWith("="))
        {
            line=line.replace(4,1,"=");
            ui->lineEdit->setText(line);
            onBtnAuto1Clicked();
            int k=10;
            while(k-->0)
            {
                MySleep(500);
                if(ui->btnAuto1->text().startsWith("save"))
                {
                    sl.append(ui->plainTextEdit->toPlainText());
                    onHideTip();
                    break;
                }
            }
            if(k<=0)
                sl.append("time out");
        }
        line = in.readLine();
    }
    file.close();
    filename = QApplication::applicationDirPath() + QDir::separator() + "bb.txt";
    QFile fileOut(filename);
    fileOut.open(QIODevice::WriteOnly|QIODevice::Text);
    foreach (QString s, sl)
    {
        fileOut.write(s.toLatin1());
    }

    fileOut.close();
    ui->btnAuto2->setText("save in file");
}

void HttpClientView::onTimer()
{
    static int idx=0;
    if(ui->plainTextEdit->toPlainText().length()>50)
    {
        timer->stop();
        QString str="#KEY,"+ui->lineEdit_2->text() +"\r\n";
        str += QDateTime::currentDateTime().toString("ddHHmmss") + "," + ui->plainTextEdit->toPlainText() +"\r\n";
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(str);
        ui->plainTextEdit->setPlainText(str);
        ui->btnAuto1->setText("save in clipboard");
        QTimer::singleShot(1500,this,SLOT(onHideTip()));
    }
    else
    {
        idx++;
        if(idx>4)
        {
            idx=0;
            timer->stop();
            ui->plainTextEdit->setPlainText("time out");
        }
    }
}

void HttpClientView::onHideTip()
{
    ui->btnAuto1->setText("One Key Clipboard");
    ui->btnAuto2->setText("One Key Generate");
}

void HttpClientView::postFinishSlot(QString url,int statusCode, QByteArray& response)
{
    int size = response.size();
    ui->plainTextEdit->appendPlainText("request finish.");
    qDebug()<<url;
    qDebug()<<QString("response code: %1, data size: %2").arg(statusCode).arg(size);
    if (size > 0) {
        //if (0 == ui->cBoxMethod->currentIndex()) {
            QString str=QString(response);
            ui->plainTextEdit->setPlainText(str);
            int p1=str.indexOf("MainPlayUrl");
            if(p1>0)
            {
                int p2=str.indexOf("720p");
                int p3=str.indexOf("MainPlayUrl",p2);
                p3+=14;
                int p4=str.indexOf("\",\"",p3);
                str=str.mid(p3,p4-p3);
                str.replace("\\u0026","&");
                ui->plainTextEdit->setPlainText(str);
                qDebug()<<p1<<p2<<p3<<p4;

            }
//        } else if (1 == ui->cBoxMethod->currentIndex()) {
//            QImage img;
//            bool res = img.loadFromData(response);
//            if (res) {
//                ui->labelImage->setAlignment(Qt::AlignCenter);
//                ui->labelImage->setPixmap(QPixmap::fromImage(img));
//            } else {
//                qDebug("error convert image from http response data!");
//            }
//        }
    }
}

void HttpClientView::httpErrorSlot(QNetworkReply::NetworkError err)
{
    qDebug()<<QString("http error: %1").arg(err);

}
